package com.huiminpay.merchant.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.huiminpay.common.cache.domain.BusinessException;
import com.huiminpay.common.cache.domain.CommonErrorCode;
import com.huiminpay.merchant.api.service.AppServiceApi;
import com.huiminpay.merchant.convert.AppCovert;
import com.huiminpay.merchant.api.dto.AppDTO;
import com.huiminpay.merchant.entity.App;
import com.huiminpay.merchant.mapper.AppMapper;
import com.huiminpay.merchant.mapper.MerchantMapper;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.UUID;
/**
 * 应用服务接口
 */
@Service
public class AppServiceImpl implements AppServiceApi {
    @Autowired
    private MerchantMapper merchantMapper;
    @Autowired
    private AppMapper appMapper;

    /**
     * 创建商户应用
     * @param appDTO
     * @return
     * @throws BusinessException
     */
    @Override
    public AppDTO createApp(AppDTO appDTO)throws BusinessException {
        if(appDTO == null  ||
                StringUtils.isEmpty(appDTO.getMerchantId()) ||
                StringUtils.isEmpty(appDTO.getAppName())){
            throw new BusinessException(CommonErrorCode.E_110006);
        }
        //根据商户id和应用名称获取应用信息
        App appDb = appMapper.selectOne(new LambdaQueryWrapper<App>().eq(App::getAppName, appDTO.getAppName())
                .eq(App::getMerchantId, appDTO.getMerchantId()));
        if (appDb==null){
            App entity = AppCovert.INSTANCE.dto2entity(appDTO);
            String appId = UUID.randomUUID().toString();
            entity.setAppId(appId);
            appMapper.insert(entity);
        }
        return appDTO;
    }


    /**
     * 根据Id获取商户应用列表
     * @param merchantId
     * @return
     * @throws BusinessException
     */
    @Override
    public List<AppDTO> findAppsByMerchantId(Long merchantId) throws BusinessException{
        List<App> apps = appMapper.selectList(new LambdaQueryWrapper<App>().eq(App::getMerchantId, merchantId));
        List<AppDTO> dtoList = AppCovert.INSTANCE.listentity2dto(apps);
        return dtoList;
    }


    /**
     * 根据Id获取商户应用信息
     * @param appId
     * @return
     * @throws BusinessException
     */
    @Override
    public AppDTO findAppById(Long appId)throws BusinessException {
        App app = appMapper.selectById(appId);
        AppDTO appDTO = AppCovert.INSTANCE.entity2dto(app);
        return appDTO;
    }
}
